<template>
	<view class="animated fadeIn faster bg-fff" style="min-height: 100vh">
		<view class="position-fixed w-100 z-index-100 pb-1" :style="{'paddingTop':$store.state.statusBarHeight+'px','backgroundColor':bgcolor}">
			<view class="px-3" :style="{'height': $store.state.titleBarHeight + 'px'}">
				<view class="d-flex d-flex-between d-flex-middle">
					<text class="iconfont icon-yonghuliebiao font40" @click="myFriend"></text>
					<view class="d-flex-item d-flex d-flex-center d-flex-middle" :style="{'height': $store.state.titleBarHeight + 'px'}">
						<text class="font36 font-bold mr-1">聊天</text>
					</view>
					<text class="iconfont icon-yonghuliebiao font40 colorfff"></text>
				</view>
			</view>
		</view>
		<view :style="{paddingTop:$store.state.statusBarHeight+'px',height: $store.state.titleBarHeight + 'px'}"></view>
		<view class="px-3 py-3">
			<view class="px-2 bg-f8 py-3 rounded15 mb-3">
				<view class="d-flex d-flex-middle mb-3" @click="gotoActivityCenter">
					<image class="rounded" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/chat05.png" style="width: 90rpx;height: 90rpx;"></image>
					<view class="d-flex d-flex-column ml-2">
						<view class="colornan font-600 mb">活动中心</view>
						<view class="font24 color666">新用户首充最高可赚500元</view>
					</view>
				</view>
				<view class="d-flex d-flex-middle mb-3" @click="crush">
					<image class="rounded" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/chat04.png" style="width: 90rpx;height: 90rpx;"></image>
					<view class="d-flex d-flex-column ml-2">
						<view class="font-600 mb">搭子心动信号</view>
						<view class="font24 color666">有人嗒一嗒，等待你回应</view>
					</view>
				</view>
				<view class="d-flex d-flex-middle" @click="gotoMesNoticePage">
					<view class="position-relative">
						<image class="rounded" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/chat09.png" style="width: 90rpx;height: 90rpx;"></image>
						<view
							v-show="$store.state.notice" 
							class="rounded position-absolute"
							style="right: 0rpx; top: 10rpx; width: 16rpx; height: 16rpx; background: red;"
						></view>
					</view>
					<view class="d-flex d-flex-column ml-2">
						<view class="colornan font-600 mb">系统通知</view>
						<view class="font24 color666 text-clamp">{{firstMes.messageContent}}</view>
					</view>
				</view>
			</view>
			<view v-if="conversationList.length>0" @click="goChat(conversation.userProfile)" class="d-flex bg-f8 p-2 mb-3 rounded15 d-flex-middle d-flex-between" v-for="(conversation,cindex) in conversationList" :key="cindex">
				<view class="d-flex d-flex-middle">
					<view class="position-relative mr-1">
						<image @click.stop="user(conversation.userProfile.userID)" class="rounded" :src="conversation.userProfile.avatar || 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241220111921-8eee693f-83b2-41d6-bf0c-3683248035f7.jpg'" style="width: 110rpx;height: 110rpx;"></image>
						<view v-show="conversation.unreadCount" class="position-absolute rounded" style="width: 15rpx; height: 15rpx; background: red; top: 10rpx; right: 10rpx;"></view>
					</view>
					<view class="d-flex d-flex-column">
						<view class="mb font-500 text-ellipsis" style="max-width: 350rpx;">{{conversation.userProfile.nick || '嗒友'}}</view>
						<text class="font20 color999" v-if="conversation.lastMessage.type=='TIMTextElem'">{{conversation.lastMessage.messageForShow}}</text>
						<view class="font20 color999" v-else>
							<!-- #ifdef MP-WEIXIN -->
								<text v-if="conversation.lastMessage.payload.data == 'GIFT'">[礼物]</text>
								<text v-else>[图片]</text>
							<!-- #endif -->
							<!-- #ifdef APP -->
							<text v-if="conversation.lastMessage.payload?.data == 'GIFT'">[礼物]</text>
							<text v-else>[图片]</text>
							<!-- #endif -->
						</view>
					</view>
				</view>
				<text class="font22 color71 pr-1">{{getDateString(conversation.lastMessage.lastTime)}}</text>
			</view>
			<view class="d-flex d-flex-center d-flex-middle" style="padding-top: 260rpx;" v-if="conversationList.length == 0">
				<view class="d-flex d-flex-center d-flex-column d-flex-middle">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png" mode="widthFix" style="width: 130rpx;"></image>
					<text class="color999 font24 mt-1">暂无聊天信息</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import store from '@/store/index.js';
	import { otherApi } from '../../http/other';
	import {dateUtils} from '@/util/util.js';
	export default {
		data() {
			return {
				bgcolor:'transparent',
				conversationList:[],
				firstMes: {}
			}
		},
		onPageScroll(e) {
			let scrollTop = e.scrollTop
			if (scrollTop > 10) {
				this.bgcolor = '#ffffff'
			}else{
				this.bgcolor = 'transparent'
			}
		},
		computed:{
			getDateString(){
				return function fn(value){
					let now = new Date().getTime();
					let old = value
					let	oldTime = 0
					if (typeof value === 'number') {
						oldTime = old*1000;
					}
					if (typeof value === 'string') {
						oldTime = new Date(value.replace(/-/g, '/')).getTime();
					}
					return dateUtils.humanize(now - oldTime);
				}
			}
			
		},
		onShow() {
			this.getConversationList();
			this.queryFirstMes()
		},
		onReady() {
		},
		onLoad() {
			let that = this
			uni.$on('im-page', data => {
				that.getConversationList();
				let totalUnreadCount = String(that.$tim.getTotalUnreadMessageCount());
				uni.setTabBarBadge({
					index: 3,
					text: totalUnreadCount,
				});
				store.commit('setUnReadCount', totalUnreadCount);
				uni.setStorageSync('UnReadCount', totalUnreadCount);
			})
		},
		methods: {
			noAction(){
				uni.showToast({
					title:'活动暂未开发！',
					icon:'none'
				})
			},
			crush(){
				uni.navigateTo({
					url:'/pagesMain/mes-CardiacSignal/mes-CardiacSignal'
				})
			},
			deleteCn(){
				let that = this
				that.$tim.deleteConversation('C2C30').then((imResponse) => {
					console.log('删除会话'+imResponse.data.conversationID)
				}).catch(function(imError) {
					console.warn('删除会话失败的相关信息:', imError);
				});
			},
			async queryFirstMes(){
				let params = {
					messageType: 1,
					pageIndex: 1,
					pageSize: 1
				}
				let res = await otherApi.GetMesNotice(params)
				res.records.forEach(i => {
					i.transmissionContent = JSON.parse(i.transmissionContent)
				})
				this.firstMes = res.records[0]
				console.log(this.firstMes);
			},
			myFriend(){
				uni.navigateTo({
					url:'/message/friend/friend'
				})
			},
			addFriend(){
				let that = this
				that.$tim.addFriend({
					to: 'administrator',
					source: 'AddSource_Type_App',
					type: 'Add_Type_Both',
				}).then((imResponse) => {
					// 添加好友的请求发送成功
					uni.showToast({
						title:'添加好友成功！'
					})
					const { code } = imResponse.data;
					if (code === 30539) {
						// 30539 说明 user1 设置了【需要经过自己确认对方才能添加自己为好友】，此时 SDK 会触发 TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED 事件
					} else if (code === 0) {
						// 0 说明 user1 设置了【允许任何人添加自己为好友】，此时 SDK 会触发 TIM.EVENT.FRIEND_LIST_UPDATED 事件
						console.log('添加好友成功！')
					}
				}).catch((imError) => {
					console.warn('addFriend error:', imError);
				});
			},
			goChat(profile){
				// let flag = this.$store.state.user.realName === '' || this.$store.state.user.realName === null;
				let flag = false
				if (flag) {
				    console.log("没有实名认证");
					uni.showModal({
						content: '你还没有完成实名认证，请先完成实名认证？',
						confirmText: '去实名',
						success: (res) => {
							if (res.confirm) {  
								uni.navigateTo({
									url: `/pagesApp/RealName/RealName`
								});
							}
						}
					});
				} else {
					// 如果已经实名认证，执行其他操作
					let item = {
						id: profile.userID,
						name: profile.nick,
						avatar: profile.avatar,
						conversationID: 'C2C'+profile.userID,
						type:'C2C'
					}
					this.ClearUnreadMessages(item)
				}
			},
			// 点击头像进入个人页
			user(uid) {
				console.log(uid);
				if (uid == this.$store.state.user.uid) {
					uni.switchTab({
						url: `/pages/user/user`
					});
				} else {
					uni.navigateTo({
						url: `/pagesMain/HomePage/HomePage?id=${uid}`
					});
				}
			},
			getConversationList(){
				let that = this
				that.$tim.getConversationList().then(function(imResponse) {
					that.conversationList = imResponse.data.conversationList
					console.log('conversationList',that.conversationList)
				}).catch(function(imError) {
					console.warn('获取会话列表失败的相关信息:', imError);
				});
			},
			ClearUnreadMessages(item) {
				let that = this
				let promise = that.$tim.setMessageRead({conversationID: item.conversationID});
				promise.then(function(imResponse) {
					// 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
					console.log('setMessageRead sussess:', imResponse);
					let totalUnreadCount = String(that.$tim.getTotalUnreadMessageCount());
					setTimeout(() => {
						if(totalUnreadCount != '0') {
							uni.setTabBarBadge({
								index: 3,
								text: totalUnreadCount,
							});
						} else {
							uni.removeTabBarBadge({
								index: 3,
							});
						}
						store.commit('setUnReadCount', totalUnreadCount)
						uni.setStorageSync('UnReadCount', totalUnreadCount);
						setTimeout(() => {
							uni.navigateTo({
								url:'/message/im/im?to=' + encodeURIComponent(JSON.stringify(item))
							})
						}, 200)
					}, 200)
				}).catch(function(imError) {
					// 已读上报失败
					console.warn('setMessageRead error:', imError);
				});
			},
			openIm(){
				let item = {
					id: 'hellowk',
					name: 'hellowk',
					avatar: 'https://gameplus-platform.cdn.bcebos.com/gameplus-platform/upload/file/img/ed39ad04e7655cbea70fe406f70a7fe8/ed39ad04e7655cbea70fe406f70a7fe8.png',
					conversationID: 'C2Chellowk',
					type: 'C2C'
				}
				let iitem = {
					id: 'weCat',
					name: 'weCat',
					avatar: 'https://gameplus-platform.cdn.bcebos.com/gameplus-platform/upload/file/img/ed39ad04e7655cbea70fe406f70a7fe8/ed39ad04e7655cbea70fe406f70a7fe8.png',
					conversationID: 'C2CweCat',
					type: 'C2C'
				}
				uni.navigateTo({
					url:'/message/im/im?to=' + encodeURIComponent(JSON.stringify(iitem))
				})
			},
			gotoCardiacSigin() {
				uni.navigateTo({
					url:'/pagesMain/mes-CardiacSignal/mes-CardiacSignal'
				})
			},
			gotoActivityCenter() {
				uni.navigateTo({
					url: '/pagesMain/my-ActivityCenter/my-ActivityCenter'
				})
			},
			openHomePage() {
				uni.navigateTo({
					url:'/pagesMain/HomePage/HomePage'
				})
			},
			gotoMesNoticePage() {
				uni.navigateTo({
					url: '/pagesApp/MesNotice/MesNotice'
				})
			}
		}
	}
</script>

<style scoped>
.blueSrch{
	background: #CFF0FB;
	border: 1px solid #46C4FF;
	color: #46C4FF;
	height: 60rpx;
	border-radius: 30rpx;
}
</style>
